<template>
  <div class="page">
    <loading-hard></loading-hard>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import Blocks from '@/components/blocks'
import LoadingHard from '@/components/loading-hard'
import base from '@/mixins/base'

export default {
  mixins: [base],
  data () {
    return {
      runticker: 0,
      outtime: 0,
      isPageShow: false,
      taskId: 0
    }
  },
  components: {
    Blocks,
    LoadingHard
  },
  computed: {
    ...mapGetters('progress', [
      'progress'
    ]),
    ...mapGetters('task', [
      'task'
    ]),
    ...mapGetters([
      'loginer',
      'isLogined',
      'isNeedAuthUserInfo'
    ]),
    isReady () {
      if (!this.isPageShow) return false
      if (!this.isLogined) return false
      if (!this.isNeedAuthUserInfo) return false
      if (!this.taskId) return false
      return this.runticker
    }
  },
  onShow () {
    this.it = setInterval(() => {
      this.runticker++
    }, 300)
    this.isPageShow = true
    let {taskId} = this.$root.$mp.query
    this.taskId = taskId
  },
  onUnload () {
    this.isPageShow = false
    if (this.it) clearInterval(this.it)
  },
  onHide () {
    this.isPageShow = false
    if (this.it) clearInterval(this.it)
  },
  watch: {
    async isReady (nv) {
      if (!nv) return
      if (this.runing) return
      this.runing = true
      await this.fetchById(this.taskId)
      let isTaskOwner = parseInt(this.loginer.id) === this.task.creator.id
      if (isTaskOwner) {
        wx.redirectTo({
          url: '/pages/task-progresses/main?taskId=' + this.taskId
        })
        this.runing = false
        if (this.it) clearInterval(this.it)
        return
      }
      await this.createByTaskId(this.taskId)
      wx.redirectTo({
        url: '/pages/progress/main?progressId=' + this.progress.id
      })
      this.runing = false
      if (this.it) clearInterval(this.it)
    }
  },
  methods: {
    ...mapActions('task', [
      'fetchById'
    ]),
    ...mapActions('progress', [
      'createByTaskId'
    ])
  }
}
</script>

<style scoped>
.page {
  background-color: white;
  height: 100%;
}
</style>
